package org.dealpdf.sample;

import com.google.zxing.WriterException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.dealpdf.model.OutboundDetail;
import org.dealpdf.utils.PdfUtil;
import org.dealpdf.utils.WordUtil;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OutboundDocumentGenerator {
    public static void main(String[] args) {
        try {
            // PDF 处理
            generatePdf();
            // Word 处理
            generateWord();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void generatePdf() throws IOException, DocumentException, WriterException {
        String templatePath = "src/main/resources/OutboundTemplate.pdf";
        String outputPath = "outbound_byPdf.pdf";
        PdfReader reader = new PdfReader(templatePath);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputPath));
        PdfContentByte canvas = stamper.getOverContent(1);

        // 填充基础信息
        Map<String, String> data = getBaseInfoFromApi();
        System.out.println("Data for PDF: " + data); // 调试输出
        drawBaseInfo(canvas, data, reader); // 基于模板调整基础信息

        // 填充表格
        List<OutboundDetail> details = generateSampleDetails();
        PdfUtil.addTable(canvas, details); // 启用表格绘制

        // 添加二维码
        String qrContent = "OrderID: " + data.get("orderCode") + "\nDate: " + data.get("outboundDate");
        PdfUtil.addQRCode(canvas, qrContent);

        // 添加水印
        PdfUtil.addWatermark(stamper, "ikun");

        stamper.close();
        reader.close();
    }

    private static void generateWord() throws IOException, WriterException, InvalidFormatException {
        String templatePath = "src/main/resources/OutboundTemplate.docx";
        String wordOutputPath = "outbound_byWord.docx";
//        String pdfOutputPath = "outbound_document.pdf";

        try (FileInputStream fis = new FileInputStream(templatePath);
             XWPFDocument doc = new XWPFDocument(fis);
             FileOutputStream fosWord = new FileOutputStream(wordOutputPath)) {

            // 填充基础信息
            Map<String, String> data = getBaseInfoFromApi();
            System.out.println("Data to replace: " + data); // 调试输出
            WordUtil.replacePlaceholders(doc, data);
            data.put("reviewer", "王五"); // 确保 reviewer 有值

            // 填充表格
            List<OutboundDetail> details = generateSampleDetails();
            WordUtil.addTable(doc, details);

            // 添加二维码
            String qrContent = "OrderID: " + data.get("orderCode") + "\nDate: " + data.get("outboundDate");
            WordUtil.addQRCode(doc, qrContent);

            // 保存 Word 文档
            doc.write(fosWord);

//            // 转换为 PDF (暂注释，待完善)
//            Document pdfDoc = new Document();
//            PdfWriter.getInstance(pdfDoc, new FileOutputStream(pdfOutputPath));
//            pdfDoc.open();
//            pdfDoc.close();
        }
    }

    private static Map<String, String> getBaseInfoFromApi() {
        Map<String, String> data = new HashMap<>();
        data.put("orderCode", "BF-03-05-1");
        data.put("outboundDate", "2025-07-11");
        data.put("customerName", "某某公司");
        data.put("warehouseCode", "CK_7525080416537318");
        data.put("creator", "张三");
        data.put("auditor", "李四");
        data.put("createTime", "2025-07-11 01:00");
        data.put("outboundOrderId", "13500135001");
        return data;
    }

    private static List<OutboundDetail> generateSampleDetails() {
        List<OutboundDetail> details = new ArrayList<>();
        details.add(new OutboundDetail("BF-03-05-1", "no1", "34CrNiMo6", "原材料", 6.60, 100.00));
        details.add(new OutboundDetail("BF-03-05-2", "no2", "35CrMo", "半成品", 5.5, 120.00));
        details.add(new OutboundDetail("BF-03-05-3", "no3", "Q235", "成品", 10.0, 80.00));
        return details;
    }

    /**
     * 绘制基础信息到 PDF，基于模板中的占位符位置
     * @param canvas PDF 内容层
     * @param data 基础信息数据
     * @param reader PDF 读取器，用于获取页面信息
     * @throws DocumentException 文档异常
     * @throws IOException 输入输出异常
     */
    private static void drawBaseInfo(PdfContentByte canvas, Map<String, String> data, PdfReader reader) throws DocumentException, IOException {
        float margin = 50;
        float pageHeight = canvas.getPdfDocument().getPageSize().getHeight();
        float initialY = pageHeight - margin - 100; // 调整初始 y 坐标，靠近表格上方，需根据模板微调

        com.itextpdf.text.pdf.BaseFont baseFont = com.itextpdf.text.pdf.BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", com.itextpdf.text.pdf.BaseFont.NOT_EMBEDDED);

        // 覆盖占位符的白色矩形
        String[] placeholders = {
                "[orderCode]", "[outboundDate]", "[customerName]", "[warehouseCode]",
                "[creator]", "[auditor]", "[createTime]", "[outboundOrderId]"
        };
        float[] yPositions = {
                initialY, initialY - 20, initialY - 40, initialY - 60,
                initialY - 80, initialY - 100, initialY - 120, initialY - 140
        }; // 假设每行间隔 20 像素，需调整
        canvas.setColorFill(com.itextpdf.text.BaseColor.WHITE); // 填充白色覆盖占位符
        for (int i = 0; i < placeholders.length; i++) {
            canvas.rectangle(margin - 5, yPositions[i] - 15, 200, 20); // 假设占位符宽度 200 像素
        }
        canvas.fill();

        // 绘制新文本
        canvas.beginText();
        canvas.setFontAndSize(baseFont, 12);
        canvas.setColorFill(com.itextpdf.text.BaseColor.BLACK); // 确保文本可见
        for (int i = 0; i < placeholders.length; i++) {
            String key = placeholders[i].replace("[", "").replace("]", "");
            String value = data.getOrDefault(key, placeholders[i]); // 替换占位符
            canvas.showTextAligned(Element.ALIGN_LEFT, value, margin, yPositions[i], 0);
            System.out.println("Drawing: " + key + " = " + value + " at y=" + yPositions[i]); // 调试输出
        }
        canvas.endText();
    }
}